﻿using BySoft.Server.Business;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.MasteData
{
    public partial class ProductAdd : AuthBasePage
    {
        public string sequenceName
        {
            get { return "MD_Product"; }
        }
      
       
        private string m_strTbl = "MD_Product";
        private string m_strMainKey = "ProductID";

        #region Attachment File

        /// <summary>
        /// 图纸文件的datatable     与upProductFile 统一
        /// </summary>
        protected DataTable DtDUpFile
        {
            get
            {
                if (Session[SessionMapName] != null)
                {
                    return (DataTable)Session[SessionMapName];
                }
                else
                {
                    return CreateUpFileDT();
                }
            }
            set
            {
                Session[SessionMapName] = value;
            }
        }

        /// <summary>
        /// 技术文件的datatable
        /// </summary>
        public DataTable DtTechFile
        {
            set { Session[SessionTechName] = value; }
            get
            {
                if (Session[SessionTechName] == null)
                {
                    return CreateUpFileDT();
                }
                else
                {
                    return (DataTable)Session[SessionTechName];
                }
            }
        }




        private DataTable CreateUpFileDT()
        {
            //DataTable dtProcessDetail = new DataTable();
            //dtProcessDetail.Columns.Add("AttachmentID");
            //dtProcessDetail.Columns.Add("FileType");
            //dtProcessDetail.Columns.Add("FileSize");
            //dtProcessDetail.Columns.Add("UpDateTime");
            //dtProcessDetail.Columns.Add("FileURL");
            //dtProcessDetail.Columns.Add("FileName");
            //dtProcessDetail.Columns.Add("FormType");
            //dtProcessDetail.Columns.Add("FormID");
            //dtProcessDetail.Columns.Add("Status");
            //dtProcessDetail.Columns.Add("OpenURL");
            //return dtProcessDetail;

            return MdProduct.CreateUpFileDT();

        }
      #endregion



        static string SessionMapName = "";
        static string SessionTechName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                txtProductID.Attributes.Add("readonly", "true");

                SessionMapName = MdProduct.QuerySessionFileName("5");
                SessionTechName = MdProduct.QuerySessionFileName("6");

                Session[SessionMapName] = null;

                Session[SessionTechName] = null;


                BindDDLProductType();
                ChangeProductID();
                //BindData();
                BindMapFileData();
                BindTechFileData();
            }
         
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();iframeAutoFit();");
        }


        protected void btnAddMapFileHide_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindMapFileData()
        {
            try
            {

                foreach (DataRow dr in DtDUpFile.Rows)
                {
                    
                    dr["FormID"] = txtProductID.Text.Trim();
                }
                grdResultMap.DataSource = DtDUpFile;
                grdResultMap.DataBind();
                UIHelper.RunScript(this.Page, "iframeAutoFit(); ");
            }
            catch { }
        }



        protected void btnAdTechFileHide_Click(object sender, EventArgs e)
        {
            try
            {
                BindTechFileData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindTechFileData()
        {
            foreach (DataRow dr in DtTechFile.Rows)
            {
                
                dr["FormID"] = txtProductID.Text.Trim();
            }
            grdResultTech.DataSource = DtTechFile;
            grdResultTech.DataBind();

            UIHelper.RunScript(this.Page, "iframeAutoFit(); ");

        }

        //protected void btnRead_Click(object sender, EventArgs e)
        //{
        //    if (lstFile.Items.Count > 0)
        //    {
        //        if (!string.IsNullOrEmpty(lstFile.SelectedValue.Trim()))
        //        {
        //            DataTable dtProcessDetail = DtDUpFile.Copy();
        //            DataRow[] drs = dtProcessDetail.Select("AttachmentID='" + lstFile.SelectedValue.Trim() + "'");
        //            if (drs.Length > 0)
        //            {
        //                DataRow dr = drs[0];
        //                string path = "/UpFile/";
        //                path += dr["FormType"] + "/" + dr["FileURL"];
        //                path = Request.Url.Scheme + "://" + Request.Url.Authority + path;
        //                UIHelper.RunScript(this, "window.open('" + path + "')");
        //            }
        //        }
        //        else
        //        {
        //            UIHelper.AlertMessage(this.Page, "请先选择要查看的附件！");
        //        }
        //    }
        //    else
        //    {
        //        UIHelper.AlertMessage(this.Page, "请先上传附件！");
        //    }
        //}

       
        private void ChangeProductID()
        {
            //by zhang
            this.txtProductID.Text = ClsComm.GetMaxSequenceID(sequenceName + ddlProductType.SelectedValue.Trim(), ddlProductType.SelectedValue.Trim(), 4) ; 
        }

        private void BindDDLProductType()
        {
            DataTable dt = MdProducttype.GetMdProducttypeAll().Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                this.ddlProductType.DataSource = dt;
                this.ddlProductType.DataTextField = "ProductTypeName";
                this.ddlProductType.DataValueField = "ProductTypeID";
                this.ddlProductType.DataBind();
            }
           
            UIHelper.InsertFirstItem(ddlProductType);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //GetGridViewData();
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写产品资料！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.txtProductID.Text.Trim()))
                {
                   if (!ValidateData()){
                       return;
                   }
                    
                    MdProductEntity product = new MdProductEntity();
                    product.ProductID = this.txtProductID.Text.Trim();
                    product.ProductName = this.txtProductName.Text.Trim();
                    product.Unit = this.txtUnit.Text.Trim();
                    product.Specifications = this.txtSpecifications.Text.Trim();
                    product.ProductTypeID = this.ddlProductType.SelectedValue.Trim();
                    product.SafeStock = GetDecimal(txtSafeStock);
                    product.OutSide = GetDecimal(txtOutSide); ;
                    product.InSide = GetDecimal(txtInSide);
                    product.Status = "1";
                    product.CreateDate = DateTime.Now;
                    product.CreateUserID= CurrentUser.UserID;
                    product.CreateUserName = CurrentUser.UserName;
                   

                    List<MdAttachmentEntity> dtResultMapFile = GetDataViewFiles(product.ProductID, DtDUpFile, "ProductMap");
                    List<MdAttachmentEntity> dtResultTechFile = GetDataViewFiles(product.ProductID,DtTechFile , "ProductTech");


                    if (MdProduct.Save(product, dtResultMapFile, dtResultTechFile,true))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName + ddlProductType.SelectedValue.Trim());
                        base.LogAction(BaseEnum.ActionType.Add, product.ProductID, true, null, new EntityBase[] { product });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../MasteData/ProductList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }

            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        private static List<MdAttachmentEntity>  GetDataViewFiles(string  strProductID, DataTable dt,string strFormType)
        {
            List<MdAttachmentEntity> lstyFile = new List<MdAttachmentEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow drItem in dt.Rows)
                {
                    MdAttachmentEntity Detailentity = new MdAttachmentEntity();
                    Detailentity.AttachmentID = Guid.NewGuid().ToString();
                    Detailentity.FileType = CommonMethod.GetString(drItem["FileType"]);
                    Detailentity.FileSize = Convert.ToInt32(drItem["FileSize"]);
                    Detailentity.UpDateTime = DateTime.Now;
                    Detailentity.FileURL = CommonMethod.GetString(drItem["FileURL"]);
                    Detailentity.FileName = CommonMethod.GetString(drItem["FileName"]);
                    Detailentity.FormType = strFormType;//"entity";
                    Detailentity.FormID = strProductID;
                    Detailentity.Status = "1";
                    lstyFile.Add(Detailentity);
                }
            }
            return lstyFile;
           
        }

        protected void ddlProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeProductID();
        }


        protected void btnAddhid_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();

            }
            catch (Exception ex) { }

        }
       
        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                } 
            }
        }
      

        protected void grdResultMap_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                   
                       // GetGridViewData();
                        DataTable dtTemp = DtDUpFile.Copy();
                       
                        DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strCode + "'");
                        if (drsSelect != null && drsSelect.Length > 0)
                        {
                            dtTemp.Rows.Remove(drsSelect[0]);
                            dtTemp.AcceptChanges();
                            DtDUpFile = dtTemp.Copy();
                            BindMapFileData();
                        }
                       
                        UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                  
                    break;
                
                default:
                    break;
            }
        }

      

        //Tech file Delete
        protected void grdResultTech_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                   
                        // GetGridViewData();
                        DataTable dtTemp = DtTechFile.Copy();

                        DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strCode + "'");
                        if (drsSelect != null && drsSelect.Length > 0)
                        {
                            dtTemp.Rows.Remove(drsSelect[0]);
                            dtTemp.AcceptChanges();
                            DtTechFile = dtTemp.Copy();
                            BindTechFileData();
                        }

                        UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                   
                    break;

                default:
                    break;
            }
        }


        #region 数据有效验证
        private bool ValidateData()
        {
            string strMention = "";




            if (string.IsNullOrEmpty(ddlProductType.SelectedValue))
            {
                strMention += "请选择产品类别！";
            }

            if (string.IsNullOrEmpty( txtProductName.Text.Trim()))
            {
                strMention += "请输入产品名称！";
            }

            MdProduct entity = new MdProduct();
            if (entity.IsIDExists(this.txtProductID.Text.Trim()))
            {
                ChangeProductID();
                strMention += "产品编号已存在，请重新保存！";

            }

            if (entity.IsNameExists(this.txtProductName.Text.Trim(), ""))
            {
                strMention += "产品名称已存在，请重新输入！";

            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }


        #endregion
    }
}